#include <File.h>
#include <System.h>

FcbMsg::FcbMsg(FCB fcb, string filename)
{
    this->name = filename;
    this->fcb =fcb;
}

File::File( FCB fcb, string filename) : FcbMsg(fcb, filename)
{
    this->getPos = 0;
    this->putPos = 0;
}


//文件大小
int FcbMsg::size()
{
    if(isExist())
    {
        return fcb.bytes;
    }
    return 0;
}

//获得创建时间
DateTime FcbMsg::getCreateTime()
{
    if(isExist())
    {
        return DateTime(fcb.create_time);
    }
    return DateTime();
}

//获得更新时间
DateTime FcbMsg::getUpdateTime()
{
    if(isExist())
    {
        return DateTime(fcb.update_time);
    }
    return DateTime();
}

//获得访问时间
DateTime FcbMsg::getVisitTime()
{
    if(isExist())
    {
        return DateTime(fcb.visit_time);
    }
    return DateTime();
}

//获得状态
int FcbMsg::getState()
{
    if(isExist())
    {
        return fcb.state;
    }
    return 0;
}

//文件是否存在
bool FcbMsg::isExist()
{
	return true;
}


//获得名字
string FcbMsg::getName()
{
	return this->name;
}

//获得读位置
int File::tellg()
{
	return this->getPos;
}

//获得写位置
int File::tellp()
{
	return this->putPos;
}

//设置读位置
void File::seekg(int pos)
{
	if(pos < 0) pos = 0;
	if(pos > this->size()) pos = size();
	this->getPos = pos;
}

//设置写位置
void File::seekp(int pos)
{
	if(pos < 0) pos = 0;
	if(pos > this->size()) pos = size();
	this->putPos = pos;
}

//是否到了文件尾
bool File::eof()
{
	if(getPos == size() || putPos == size())
	{
		return true;
	}
	
	return false;
}

//读取一定字节
int File::read(char* data, int bytes)
{
	string diskname = this->disk;
	if(getPos + bytes > size()) bytes = size() - getPos;	  //规范读取的大小
	int offsetData = 0;
	while(bytes > 0)
	{
		int count = readFile(diskname, fcb, data + offsetData, getPos, bytes > 1024 ? 1024 : bytes);
		offsetData += count;
		getPos += count;
		bytes -= count;
	}
	return offsetData;
}

//写一定的字节
int File::write(char* data, int bytes)
{
	string diskname = this->disk;
	int offsetData = 0;
	while(bytes > 0)
	{ 
		int count = writeFile(diskname, fcb, data + offsetData, putPos, bytes > 1024 ? 1024 : bytes);
		if(count == -1)   //如果写失败，则可能是虚拟磁盘满了
		{
			return offsetData;
		}
		offsetData += count;
		putPos += count;
		bytes -= count;
	}
	return offsetData;
}
